package org.topteam.oschat.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.iq80.leveldb.WriteBatch;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.topteam.oschat.dao.Batch;
import org.topteam.oschat.dao.KvDao;
import org.topteam.oschat.entity.Band;
import org.topteam.oschat.entity.User;
import org.topteam.oschat.entity.UserRelation;
import org.topteam.oschat.service.IUserService;
import org.topteam.oschat.service.UserStatue;

import com.alibaba.fastjson.JSON;

@Service
public class UserServiceImpl implements IUserService {

	@Autowired
	private KvDao dao;

	@Override
	public User getUser(String userId) {
		String u = dao.open(User.TAG).get(userId);
		User user = JSON.parseObject(u, User.class);
		return user;
	}

	@Override
	public UserRelation getUserRelation(String userId) {
		String u = dao.open(UserRelation.TAG).get(userId);
		UserRelation relation = JSON.parseObject(u, UserRelation.class);
		return relation;
	}

	@Override
	public Map<String, List<User>> getFriends(String userId) {
		UserRelation relation = this.getUserRelation(userId);
		Map<String, List<User>> firends = new TreeMap<>();
		if (relation != null) {
			for (Band band : relation.getBands()) {
				List<User> users = new ArrayList<User>();
				for (String u : band.getUsers()) {
					User user = this.getUser(u);
					users.add(user);
				}
				firends.put(band.getName(), users);
			}
		}
		return firends;
	}

	@Override
	public void updateStat(String userId, UserStatue onLine) {
		dao.open("userstatue").put(userId, onLine.name());
	}

	@Override
	public List<String> getOnlineFirends(String userId) {
		final UserRelation relation = this.getUserRelation(userId);
		List<String> onlineFirends = new ArrayList<>();
		if (relation != null) {
			dao.open("userstatue");
			for (Band band : relation.getBands()) {
				for (String u : band.getUsers()) {
					String stat = dao.get(u);
					if (stat != null && stat.equals(UserStatue.ON_LINE.name())) {
						onlineFirends.add(u);
					}
				}
			}
		}
		return onlineFirends;
	}

}
